#!/sbin/openrc-run
# Copyright (c) 2009-2015 Funtoo Technologies
# Released under the 2-clause BSD license.

description="Sets the hostname of the machine."

depend() {
	need root
}

start()
{
	hostname=${hostname-${HOSTNAME-localhost}}
	out=$hostname
	short=${hostname%%.*}
	if [ "$short" != "$hostname" ]; then
		out="$out $short"
	fi
	if [ "$nisdomainname" != "" ]; then
		ebegin "Setting NIS domain name to $nisdomainname"
		nisdomainname $nisdomainname
		eend $? "Failed to set the NIS domain name"
	fi
	if [ "$short" != "localhost" ]; then
		out="$out localhost"
	fi
	if [ "$hostname" != "localhost.localdomain" ]; then
		out="$out localhost.localdomain"
	fi
	[ -n "$aliases" ] && out="$out $aliases"
	ebegin "Configuring /etc/hosts"
	[ -e /etc/hosts ] && sed -i -e '/[[:space:]]*127.0.0.1[[:space:]]/d' -e '/[[:space:]]*::1[[:space:]]/d' /etc/hosts
	cat <<END >> /etc/hosts
127.0.0.1	$out
::1		$out
END
	chmod 0644 /etc/hosts
	eend $?
	[ "$RC_SYS" = "LXC" ] && return 0
	ebegin "Setting hostname to $hostname"
	hostname "$short"
	eend $? "Failed to set the hostname"
}
